<?php
class Tournaments {
	function __construct(){
		FunctionsHelper::includeFiles(
			array(
				ADMINISTRATOR_MODEL_DIRECTORY . 'model.php',
				ADMINISTRATOR_MODEL_DIRECTORY . 'tournament.php',
				ADMINISTRATOR_MODEL_DIRECTORY . 'tournament_category.php',
				ADMINISTRATOR_MODEL_DIRECTORY . 'match.php',
				ADMINISTRATOR_MODEL_DIRECTORY . 'round.php',
				ADMINISTRATOR_MODEL_DIRECTORY . 'country.php',
				ADMINISTRATOR_MODEL_DIRECTORY . 'international_match.php',
				ADMINISTRATOR_CONTROLLER_DIRECTORY . 'players.php',
				ADMINISTRATOR_CONTROLLER_DIRECTORY . 'countries.php',
				ADMINISTRATOR_MODEL_DIRECTORY . 'player.php'
			)
		);
	}
	
	public function getAll(){
		$arrResult = Tournament::getAll();
		$arrTournaments = array();
		foreach($arrResult as $tournament){
			$tournament['class'] = $tournament['class_id'];
			$tournamentSelected = new Tournament($tournament);
			$tournamentSelected->getTournamentClass();
			$tournamentSelected->getIfHasMatches();
			$arrTournaments[] = $tournamentSelected;
		}
		return $arrTournaments;
	}
	
	public function getTournament($arrInitialValue = null){
		if (empty($arrInitialValue))
			return new Tournament();

		$tournament = new Tournament($arrInitialValue);
		$tournament = $tournament->getTournament();
		$tournament = $tournament[0];
		
		foreach ($tournament as $key => $value){
			$tournament[$key] = utf8_encode($value);
		}

		if (empty($tournament))
			return new Tournament();

		$tournament['class'] = $this->getClassOfTournament($tournament);
		
		return new Tournament($tournament);
	}
	
	public function getRounds(){
		$round = new Round();
		return $round->getAllRounds();
	}
	
	public function getCategories(){
		$arrCategories = array();

		$tournamentCategories = TournamentCategory::getAll();
		 foreach ($tournamentCategories as $category){
		 	$arrCategories[] = new TournamentCategory($category);
		 }
		 
		 return $arrCategories;
	}
	
	private function getClassOfTournament($tournament){
		$tournamentClass = new TournamentCategory(
			array(
				'class_id' => $tournament['class_id']
			) 
		);
		$tournamentClass = $tournamentClass->getClass();

		return new TournamentCategory($tournamentClass[0]);
	}
	
	public function createTournament($arrInitialValues = null){
		if (empty($arrInitialValues))
			return 1;

		$arrInitialValues['class'] = new TournamentCategory($arrInitialValues);
		$arrInitialValues['initial_date'] = FunctionsHelper::adaptDBFormatDate($arrInitialValues['initial_date']);
		$arrInitialValues['final_date'] = FunctionsHelper::adaptDBFormatDate($arrInitialValues['final_date']);

		if (!empty($arrInitialValues['image'])){
			$arrInitialValues['image']['name'] = FunctionsHelper::filesFormatName(utf8_decode($arrInitialValues['image']['name']));
			$arrImage = array(
				'newTMP' => $arrInitialValues['image']['tmp_name'],
				'newName' => $arrInitialValues['image']['name'] 
			);
			$this->copyImage($arrImage);

			$arrInitialValues['image'] = $arrInitialValues['image']['name'];
		}

		$tournament = new Tournament($arrInitialValues);
		return $this->insertOrModify($tournament, $arrInitialValues['createFemale'], 'I');
	}
	
	public function updateTournament($arrInitialValues = null){
		if (empty($arrInitialValues)) {
			return 1;
		}

		$arrInitialValues['initial_date'] = FunctionsHelper::adaptDBFormatDate($arrInitialValues['initial_date']);
		$arrInitialValues['final_date'] = FunctionsHelper::adaptDBFormatDate($arrInitialValues['final_date']);
		$arrInitialValues['class'] = new TournamentCategory($arrInitialValues);

		if (!isset($arrInitialValues['active'])) {
			$arrInitialValues['active'] = 0;
		}
		$tournament = new Tournament($arrInitialValues);

		
		if (!empty($arrInitialValues['deleteImage'])){
			$currentImage = $tournament->getCurrentImage();
			$arrImage = array(
				'currentImage' => $currentImage[0]['image']
			);
			$this->deleteImage($arrImage);
			$tournament->setImage('');
			$tournament->updateImage();
		
			if (!empty($arrInitialValues['image']['name'])){
				$arrInitialValues['image']['name'] = FunctionsHelper::filesFormatName(utf8_decode($arrInitialValues['image']['name']));
				$arrImage = array(
					'newTMP' => $arrInitialValues['image']['tmp_name'],
					'newName' => $arrInitialValues['image']['name']
				);

				$this->copyImage($arrImage);
				$tournament->setImage($arrImage['newName']);
				$tournament->updateImage();
			}
		}

		if (!isset($arrInitialValues['createFemale'])) {
			$arrInitialValues['createFemale'] = 0;
		}
		return $this->insertOrModify($tournament, $arrInitialValues['createFemale'], 'U');
	}
	
	public function deleteTournament($id){
		$tournament = new Tournament(
			array(
				'tournament_id' => $id
			)
		);
		return $tournament->delete();
	}
	
	public function activateTournament($id){
		$tournament = new Tournament(
			array(
				'tournament_id' => $id
			)
		);
		return $tournament->activate();
	}
	
	public function getAllMatches($arrInitialValues = null){
		$arrObjMatches = array ();
		$tournament = new Tournament($arrInitialValues);
		return $this->_getMatches($tournament);
	}
	
	private function _getMatches($tournament){
		$arrMatches = $tournament->getAllMatches();
		$arrObjMatches = array();
		foreach ($arrMatches as $matchFE){
			if (isset($matchFE['serie_id']))
				$hasMatches = $tournament->serieHasMatches($matchFE['serie_id']);
			$match = new stdClass();
			
			$match->Round = $this->getRound($matchFE);
			$match->Result = $matchFE['result'];
			if (strtolower($tournament->getClass()) == 'nations'){
				$match->Id = $matchFE['serie_id'];
				$match->First = $this->getNation($matchFE['country1_id']);
				$match->FirstId = $matchFE['country1_id'];
				$match->SecondId = $matchFE['country2_id'];
				$match->Second = $this->getNation($matchFE['country2_id']);
				$match->HasMatches = $hasMatches[0]['countMatches'];
				$match->Place = $matchFE['place'];
				$match->Surface = $matchFE['surface'];
			}else{
				$match->Id = $matchFE['match_id'];
				$match->HasMatches = 0;
				$match->First = $this->getPlayerName($matchFE['player1_id']);
				$match->Second = $this->getPlayerName($matchFE['player2_id']);
			}
			$arrObjMatches[] = $match;
		}
		return $arrObjMatches;
	}
	
	private function getPlayerName($playerId){
		$players = new Players();
		$player = $players->getPlayer(
			array(
				'player_id' => $playerId
			)
		);
		return $player->getName() . ' ' . $player->getSurname();
	}
	
	private function getNation($countryId){
		$countries = new Countries();
		$country = $countries->getCountry(
			array(
				'country_id' => $countryId
			)
		);
		return $country->getName();
	}
	
	public function deleteInternationalMatch($id){
		$serie = new InternationalMatch(
			array(
				'match_id' => $id
			)
		);

		$serie->deleteMatches();
		$serie->delete();
	}
	
	public function deleteMatch($id){
		$match = new Match(
			array(
				'match_id' => $id
			)
		);
		$match->delete();
	}
	
	private function getRound($arrInitialValues = null){
		$round = new Round(
			array(
				'round_id' => $arrInitialValues['round_id']
			)
		);
		$round->getRound();
		return $round;
	}
	
	private function insertOrModify($tournament, $female, $action = 'U'){	
		if ($action == 'U')
			$tournament->update();
		else
			$tournament->create();

		if ($female && !$tournament->alreadyExistsFemaleTournament()){
			$tournament->setSex('F');
			$tournament->create();
		}

		return 1;
	}

	private function deleteImage($arrPath){
		if (!empty($arrPath['currentImage']))
			@unlink(MAIN_TOURNAMENTLOGO_NEWS_DIRECTORY . $arrPath['currentImage']);
	}
	
	private function copyImage($arrPath){
		@copy($arrPath['newTMP'], MAIN_TOURNAMENTLOGO_NEWS_DIRECTORY . $arrPath['newName']);
	}
}
?>